﻿using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using Chemistry.Models;
using OPCAutomation;
using Chemistry.Tools;

namespace Chemistry.WorkFlow
{
    using GalaSoft.MvvmLight.Messaging;

    /// <summary>
    /// 磺化工艺流程-调节阀门大小,在用
    /// </summary>
    public class Snlfonation : FlowBaseAll
    {
        #region 字段

        private const int _sleepfast = 500;
        private static int _relayCommand = 0;
        private int _open = 1;
        private int _close = 0;
        private List<Step> _steps ;

        static bool _isgetoverstate1 = false;
        static bool _isgetoverstate2 = false;
        private int _reactionSecond =30;

        //组态数据
        private static double _temperatureValue = 22;
        private static double _flowOxygenValue ;
        private static double _flowSo3Value ;
        private static double _flowAlkylbenzeneValue;
        private static double _so3O2Rate ; //SO3与O2的比例
        private static double _alkylbenzeneSo3Rate; //十二烷基苯与SO3的比例
        private static double _kettleLevel;//反应釜底部液位

        //增减量
        private static double _temperature_increment = 0.5;
        private static double _temperature_decrement = 0.5;
        private static double _flow_oxygen_increment = 0.5;
        private static double _flow_so3_increment = 0.5;
        private static double _flow_alkylbenzene_increment = 0.5;
        private static double _so3o2Rate_creament;
        private static double _benSo3Rate_creament;

        //配置文件命令
        string _prefix1 = string.Empty;
        string _prefix2 = string.Empty;
        string _suffixben = string.Empty;
        string _suffixso3 = string.Empty;
        string _suffixo2 = string.Empty;
        private string _llcmd;
        private string _ylcmd;
        private string _aicmd;
        private string _fmbcmd;
        string _relaycmd ;
        int _warning1number ;
        int _warning2number ;
        int _fognumber;
        int _stirnumber;

        private Tools.Tool.FlowCommand _flowcommand; //配置文件中的Title项

        #endregion


        #region 阀门状态
        private static bool _valveOxygenState = false;
        private static bool _valveSo3State = false;
        private static bool _valveAlkylbenzeneState = false;
        private static bool _valveColdState = false;
        private static bool _valveLeftCycleState = false;
        private static bool _valveRightCycleState = false;
        private static bool _valveInAgerState = false;
        private static bool _valveStirState = false;
        private static bool _valveStopState = false;
        private static double _inputO2State = 0;//阀门量
        private static double _inputSo3State = 0;
        private static double _inputbenState = 0;
        #endregion

        #region OPCItem
        //阀门
        OPCItem _valveOxygenItem;
        OPCItem _valveSo3Item;
        OPCItem _valveAlkylbenzeneItem;
        OPCItem _valveColdItem;
        OPCItem _valveLeftCycleItem;
        OPCItem _valveRightCycleItem;
        OPCItem _valveAgerItem;
        OPCItem _valveStirItem;
        OPCItem _valveStopItem;
        private OPCItem _inputO2Item;
        private OPCItem _inputSo3Item;
        private OPCItem _inputBenItem;

        //管道
        OPCItem _flowOxygenItem;
        OPCItem _flowSo3Item;
        OPCItem _flowAlkylbenzeneItem;
        OPCItem _flowInColdItem;
        OPCItem _flowInreactorItem;  //SO3与O2混合后进入反应器的管道
        OPCItem _flowLeftCycleItem;
        OPCItem _flowRightCycleItem;
        OPCItem _flowInAgerItem;
        OPCItem _flowIndemistItem;  //排气管道

        //标签
        OPCItem _labelFlowOxygenItem;  //空气鼓风机流量
        OPCItem _labelFlowSo3Item;  //SO3流量
        OPCItem _labelFlowAlkylbenzeneItem;  //十二烷基苯流量
        OPCItem _labelTemperatureItem;  //温度标签
        OPCItem _labelRateSo3O2Item;  //SO3, O2混合气体rate
        OPCItem _labelRateBenSo3Item;  //十二烷基苯rate
        OPCItem _labelColorItem;//反应器底部液位

        //闪烁
        OPCItem _flashTemperatureItem; 
        OPCItem _flashWarningItem; 

        #endregion

        #region 初始化
        public Snlfonation(OPCServer opcserver, SerialPort port, bool isinner)
        {
            _opcServer = opcserver;
            _serialPort = port;
            Isinner = isinner;
            
            InitFiled();
            InitOPC();
            InitOpcItem();
            InitSignal();
            InitMessage();
        }

        private void InitMessage()
        {
            Messenger.Default.Register<List<ButtonInformation>>(this, MessageToken.SendButtonValue,
                (i) =>
                    {
                        _inputO2State = i.SingleOrDefault(t => t.Description == "鼓风机流量").Value;
                        _inputSo3State = i.SingleOrDefault(t => t.Description == "S03进料流量").Value;
                        _inputbenState = i.SingleOrDefault(t => t.Description == "十二烷基苯进料流量").Value;
                    });
        }

        private void InitFlowCommandData()
        {
            _flowcommand = Tool.GetFlowCommand(GetType().Name);

            _prefix1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix1").Value;
            _prefix2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "prefix2").Value;
            _llcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "llcmd").Value;
            _ylcmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "ylcmd").Value;
            _aicmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "aicmd").Value;
            _relaycmd = _flowcommand.Items.SingleOrDefault(i => i.Name == "relaycmd").Value;
            _warning1number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning1").Value);
            _warning2number = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "warning2").Value);
            _fognumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "fog").Value);
            _stirnumber = int.Parse(_flowcommand.Items.SingleOrDefault(i => i.Name == "stir").Value);
        }

        private void InitFiled()
        {
            _steps = new List<Step>();
            _temperatureValue = 22;
            _flowOxygenValue = 0;
            _flowSo3Value = 0;
            _flowAlkylbenzeneValue = 0;
            _so3O2Rate = 0; 
            _alkylbenzeneSo3Rate = 0;
            _kettleLevel = 0;

            _temperature_increment = 0.5;
            _temperature_decrement = 0.5;
            _flow_oxygen_increment = 0.5;
            _flow_so3_increment = 0.5;
            _flow_alkylbenzene_increment = 0.5;
            _so3o2Rate_creament = 0.01;
            _benSo3Rate_creament = 0.01;
        }

        private void InitOpcItem()
        {
            //阀门
            _valveOxygenItem = GetItem(FiledName.ValveO2);_valveOxygenItem.Close();
            _valveSo3Item = GetItem(FiledName.ValveSO3);_valveSo3Item.Close();
            _valveAlkylbenzeneItem = GetItem(FiledName.ValveBenzene);_valveAlkylbenzeneItem.Close();
            _valveColdItem = GetItem(FiledName.ValveCold);_valveColdItem.Close();
            _valveLeftCycleItem = GetItem(FiledName.ValveLeftCycle); _valveLeftCycleItem.Close();
            _valveRightCycleItem = GetItem(FiledName.ValveRightCycle); _valveRightCycleItem.Close();
            _valveAgerItem = GetItem(FiledName.ValveAger); _valveAgerItem.Close();
            _valveStirItem = GetItem(FiledName.ValveStir);_valveStirItem.Close();
            _valveStopItem = GetItem(FiledName.ValveStop);_valveStopItem.Close();
            //_inputO2Item = GetItem(FiledName.InputO2);
            //_inputO2Item.Write(0);
            //_inputSo3Item = GetItem(FiledName.InputSo3);
            //_inputSo3Item.Write(0);
            //_inputBenItem = GetItem(FiledName.InputBen);
            //_inputBenItem.Write(0);

            //管道
            _flowOxygenItem = GetItem(FiledName.FlowO2);_flowOxygenItem.StopFlow();
            _flowSo3Item = GetItem(FiledName.FlowSO3);_flowSo3Item.StopFlow();
            _flowAlkylbenzeneItem = GetItem(FiledName.FlowBenzene);_flowAlkylbenzeneItem.StopFlow();
            _flowInColdItem = GetItem(FiledName.FlowCold);_flowInColdItem.Close();
            _flowInreactorItem = GetItem(FiledName.FlowSO3_O2);_flowInreactorItem.Close();
            _flowLeftCycleItem = GetItem(FiledName.FlowLeftCycle);_flowLeftCycleItem.Close();
            _flowRightCycleItem = GetItem(FiledName.FlowRightCycle);_flowRightCycleItem.Close();
            _flowInAgerItem = GetItem(FiledName.FlowAger);_flowInAgerItem.Close();
            _flowIndemistItem = GetItem(FiledName.FlowIndemist);_flowIndemistItem.Close();

            //标签
            _labelFlowOxygenItem = GetItem(FiledName.LabelO2);_labelFlowOxygenItem.Write(_flowOxygenValue);
            _labelFlowSo3Item = GetItem(FiledName.LabelSO3);_labelFlowSo3Item.Write(_flowSo3Value);
            _labelFlowAlkylbenzeneItem = GetItem(FiledName.LabelBenzene);_labelFlowAlkylbenzeneItem.Write(_flowAlkylbenzeneValue);
            _labelTemperatureItem = GetItem(FiledName.LabelTemperature);_labelTemperatureItem.Write(_temperatureValue);
            _labelRateSo3O2Item = GetItem(FiledName.LabelSO3_O2);_labelRateSo3O2Item.Write(_so3O2Rate);
            _labelRateBenSo3Item = GetItem(FiledName.LabelSO3_Benzene);_labelRateBenSo3Item.Write(_alkylbenzeneSo3Rate);
            _labelColorItem = GetItem(FiledName.LabelColor);_labelColorItem.Write(0);

            //闪烁
            _flashTemperatureItem = GetItem(FiledName.FlashTemperature);_flashTemperatureItem.Close();
            _flashWarningItem = GetItem(FiledName.FlashWarning);_flashWarningItem.Close();
        }

        private async Task InitServerData()
        {
            var abnormalRusult = await GetAbnormalModel(GetType().Name);
            if (abnormalRusult != null && abnormalRusult.status == 0)
                _abnormals = abnormalRusult.abnormals;
            var d = await GetDetailModel(GetType().Name);
            if (d != null && d.status == 0)
                _details = d.details;
        }

        private void InitSignal()
        {
            if (Isinner)
            {
                ListenSignal();
                InitMessage();
                _open = 1;
                _close = 0;
            }
            else
            {
                InitFlowCommandData();
                _serialPort.DataReceived += _serialPort_DataReceived;
                InitOpcItemWithSerialPort();
                ListenSerialPort();
                _open = 48;
                _close = 49;
            }
        }
        #region InitSignal Method
        bool _isListenSingnalover;
        private void ListenSignal()
        {
            
            Task.Run(() =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    var valveOxygen = Convert.ToInt32(ReadItem(FiledName.ValveO2));
                    var valveSo3 = Convert.ToInt32(ReadItem(FiledName.ValveSO3));
                    var valveAlkylbenzene = Convert.ToInt32(ReadItem(FiledName.ValveBenzene));
                    var valveCold = Convert.ToInt32(ReadItem(FiledName.ValveCold));
                    var valveLeftCycle = Convert.ToInt32(ReadItem(FiledName.ValveLeftCycle));
                    var valveRightCycle = Convert.ToInt32(ReadItem(FiledName.ValveRightCycle));
                    var valveInAger = Convert.ToInt32(ReadItem(FiledName.ValveAger));
                    var valvestir = Convert.ToInt32(ReadItem(FiledName.ValveStir));
                    var valvestop = -1;// Convert.ToInt32(ReadItem(FiledName.ValveStop));

                    //从ExamingWindow获取  2015-11-27
                    //_inputO2State = Convert.ToDouble(ReadItem(FiledName.InputO2));
                    //_inputSo3State = Convert.ToDouble(ReadItem(FiledName.InputSo3));
                    //_inputbenState = Convert.ToDouble(ReadItem(FiledName.InputBen));

                    _valveOxygenState = valveOxygen == _open;
                    _valveSo3State = valveSo3 == _open;
                    _valveAlkylbenzeneState = valveAlkylbenzene == _open;
                    _valveColdState = valveCold == _open;
                    _valveLeftCycleState = valveLeftCycle == _open;
                    _valveRightCycleState = valveRightCycle == _open;
                    _valveInAgerState = valveInAger == _open;
                    _valveStirState = valvestir == _open;
                    _valveStopState = valvestop == _open;


                    DateTime dt = DateTime.Now;
                    Step step = new Step()
                    {
                        Status =
                        {
                            {StatusName.空气阀门, _inputO2State},
                            {StatusName.So3阀门, _inputSo3State},
                            {StatusName.十二烷基苯阀门, _inputbenState},
                            {StatusName.冷却水阀门, valveCold},
                            {StatusName.左循环阀门, valveLeftCycle},
                            {StatusName.右循环阀门, valveRightCycle},
                            {StatusName.老化器阀门, valveInAger},
                            {StatusName.循环泵阀门, valvestir},
                            {StatusName.急停按钮, valvestop},
                            {StatusName.温度, _temperatureValue},
                            {StatusName.反应器底部液位, _kettleLevel},
                            {StatusName.So3O2比例,_so3O2Rate},
                            {StatusName.苯So3比例,_alkylbenzeneSo3Rate},
                        },
                        Date = dt,
                    };
                    _isListenSingnalover = true;
                    _steps.Add(step);
                    Thread.Sleep(_sleepfast);
                }
            });
        }


        int valveOxygen = -1,
                        valveSo3 = -1,
                        valveAlkylbenzene = -1,
                        valveCold = -1,
                        valveLeftCycle = -1,
                        valveRightCycle = -1,
                        valveInAger = -1,
                        valvestir = -1,
                        valvestop = -1;

        private void _serialPort_DataReceivedTest(object sender, SerialDataReceivedEventArgs e)
        {
            Thread.Sleep(500);
            if (!_serialPort.IsOpen)
                return;
            int n = _serialPort.BytesToRead;
            byte[] data = new byte[n];
            _serialPort.Read(data, 0, data.Length);

            string temp = Encoding.Default.GetString(data);
            Console.WriteLine("收到：" + temp);
            Match match = Regex.Match(temp, @"\d{5}_\d{3}");
            Match match2 = Regex.Match(temp, @"\d{1}_\d{2}_\d{3}");
            while (match.Success ||match2.Success)
            {
                Console.WriteLine(match.Value);
                ParseSpData(match.Value);
                match = match.NextMatch();
            }

        }

        void ParseSpData(string data)
        {
            Match match = Regex.Match(data, @"\d{5}_\d{3}");
            Match match2 = Regex.Match(data, @"\d{1}_\d{2}_\d{3}");
            #region 1651协议
            if (match.Success)
            {
                string s = match.Groups[0].Value.Split('_')[1];
                int v = Convert.ToInt32(s);
                string r = Convert.ToString(v, 2).PadLeft(8, '0');
                string first = match.Groups[0].Value.Split('_')[0];

                //Console.WriteLine("receive:"+ match.Groups[0]+ "\t"+DateTime.Now.ToString("mm:ss"));


                if (first == _prefix1)
                {
                    valveSo3 = Convert.ToInt32(r[0]);
                    valveOxygen = Convert.ToInt32(r[1]);
                    valvestop = Convert.ToInt32(r[2]);
                    valvestir = Convert.ToInt32(r[3]);
                    valveRightCycle = Convert.ToInt32(r[4]);

                    _valveSo3State = valveSo3 == _open;
                    _valveOxygenState = valveOxygen == _open;
                    _valveStopState = valvestop == _open;
                    _valveStirState = valvestir == _open;
                    _valveRightCycleState = valveRightCycle == _open;
                    _isgetoverstate1 = true;
                }
                else if (first == _prefix2)
                {
                    valveCold = Convert.ToInt32(r[0]);
                    valveLeftCycle = Convert.ToInt32(r[1]);
                    valveInAger = Convert.ToInt32(r[2]);
                    valveAlkylbenzene = Convert.ToInt32(r[3]);

                    _valveColdState = valveCold == _open;
                    _valveLeftCycleState = _open == valveLeftCycle;
                    _valveInAgerState = _open == valveInAger;
                    _valveAlkylbenzeneState = _open == valveAlkylbenzene;
                    _isgetoverstate2 = true;
                }


                DateTime dt = DateTime.Now;
                Step step = new Step()
                {
                    Status =
                        {
                            {StatusName.空气阀门, valveOxygen},
                            {StatusName.So3阀门, valveSo3},
                            {StatusName.十二烷基苯阀门, valveAlkylbenzene},
                            {StatusName.冷却水阀门, valveCold},
                            {StatusName.左循环阀门, valveLeftCycle},
                            {StatusName.右循环阀门, valveRightCycle},
                            {StatusName.老化器阀门, valveInAger},
                            {StatusName.循环泵阀门, valvestir},
                            {StatusName.急停按钮, valvestop},
                            {StatusName.温度, _temperatureValue},
                            {StatusName.反应器底部液位, _kettleLevel},
                            {StatusName.So3O2比例,_so3O2Rate},
                            {StatusName.苯So3比例,_alkylbenzeneSo3Rate},
                        },
                    Date = dt,
                };
                _steps.Add(step);
            }
            #endregion

            if (match2.Success)
            {
                var nr = match2.Groups[1].Value;
                var v = Convert.ToInt32(match2.Groups[2].Value);

                if (nr == _suffixben)
                {
                    _inputbenState = v;
                    _valveAlkylbenzeneState = v > 100;
                }
                else if (nr == _suffixo2)
                {
                    _inputO2State = v / 3;
                    _valveOxygenState = v > 100;
                }
                else if (nr == _suffixso3)
                {
                    _inputSo3State = v;
                    _valveSo3State = v > 100;
                }
            }
        }

        private void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int n = _serialPort.BytesToRead;
            byte[] data = new byte[n];
            _serialPort.Read(data, 0, data.Length);

            string temp = Encoding.Default.GetString(data);

            if (temp.Contains("\n"))
            {
                Match match = Regex.Match(temp, @"\d{5}_\d{3}");
                Match match2 = Regex.Match(temp, @"\d{1}_\d{2}_\d{3}");
                #region 1651协议
                if (match.Success)
                {
                    string s = match.Groups[0].Value.Split('_')[1];
                    int v = Convert.ToInt32(s);
                    string r = Convert.ToString(v, 2).PadLeft(8, '0');
                    string first = match.Groups[0].Value.Split('_')[0];

                    //Console.WriteLine("receive:"+ match.Groups[0]+ "\t"+DateTime.Now.ToString("mm:ss"));


                    if (first == _prefix1)
                    {
                        valveSo3 = Convert.ToInt32(r[0]);
                        valveOxygen = Convert.ToInt32(r[1]);
                        valvestop = Convert.ToInt32(r[2]);
                        valvestir = Convert.ToInt32(r[3]);
                        valveRightCycle = Convert.ToInt32(r[4]);

                        _valveSo3State = valveSo3 == _open;
                        _valveOxygenState = valveOxygen == _open;
                        _valveStopState = valvestop == _open;
                        _valveStirState = valvestir == _open;
                        _valveRightCycleState = valveRightCycle == _open;
                        _isgetoverstate1 = true;
                    }
                    else if (first == _prefix2)
                    {
                        valveCold = Convert.ToInt32(r[0]);
                        valveLeftCycle = Convert.ToInt32(r[1]);
                        valveInAger = Convert.ToInt32(r[2]);
                        valveAlkylbenzene = Convert.ToInt32(r[3]);

                        _valveColdState = valveCold == _open;
                        _valveLeftCycleState = _open == valveLeftCycle;
                        _valveInAgerState = _open == valveInAger;
                        _valveAlkylbenzeneState = _open == valveAlkylbenzene;
                        _isgetoverstate2 = true;
                    }


                    DateTime dt = DateTime.Now;
                    Step step = new Step()
                    {
                        Status =
                        {
                            {StatusName.空气阀门, valveOxygen},
                            {StatusName.So3阀门, valveSo3},
                            {StatusName.十二烷基苯阀门, valveAlkylbenzene},
                            {StatusName.冷却水阀门, valveCold},
                            {StatusName.左循环阀门, valveLeftCycle},
                            {StatusName.右循环阀门, valveRightCycle},
                            {StatusName.老化器阀门, valveInAger},
                            {StatusName.循环泵阀门, valvestir},
                            {StatusName.急停按钮, valvestop},
                            {StatusName.温度, _temperatureValue},
                            {StatusName.反应器底部液位, _kettleLevel},
                            {StatusName.So3O2比例,_so3O2Rate},
                            {StatusName.苯So3比例,_alkylbenzeneSo3Rate},
                        },
                        Date = dt,
                    };
                    _steps.Add(step);
                } 
                #endregion

                if (match2.Success)
                {
                    var nr = match2.Groups[1].Value;
                    var v =Convert.ToInt32(match2.Groups[2].Value);
                   
                    if (nr == _suffixben)
                    {
                        _inputbenState = v;
                        _valveAlkylbenzeneState = v > 100;
                    }
                    else if (nr == _suffixo2)
                    {
                        _inputO2State = v/3;
                        _valveOxygenState = v > 100;
                    }
                    else if (nr == _suffixso3)
                    {
                        _inputSo3State = v;
                        _valveSo3State = v > 100;
                    }
                }
            }
        }

        private void InitOpcItemWithSerialPort()
        {
            SpAIvalue(1, _temperatureValue);
            SpAIvalue(2, _so3O2Rate);
            SpAIvalue(3, 0);
            SpFlowValue(1, 0);
            SpFlowValue(2, 0);
        }

        private void ListenSerialPort()
        {
            string chkcmd_1 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd1").Value; // "#RYW11651&";
            string chkcmd_2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "chkcmd2").Value; //"#RYW11652&";
            string fmbben = _flowcommand.Items.SingleOrDefault(i => i.Name == "fmbben").Value;
            string fmbso3 = _flowcommand.Items.SingleOrDefault(i => i.Name == "fmbso3").Value;
            string fmbo2 = _flowcommand.Items.SingleOrDefault(i => i.Name == "fmbo2").Value;

            _suffixben = fmbben.Substring(fmbben.Length - 3, 2);//阀门编号  #RFMxnn&  ->nn
            _suffixo2 = fmbo2.Substring(fmbo2.Length - 3, 2);
            _suffixso3 = _suffixso3.Substring(_suffixso3.Length - 3, 2);

            Task listSerialPortState = new Task(
                () =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        SendScannerCmd(chkcmd_1);
                        SendScannerCmd(chkcmd_2);
                        SendScannerCmd(fmbben);
                        SendScannerCmd(fmbso3);
                        SendScannerCmd(fmbo2);
                    }
                });

            listSerialPortState.Start();
        }

        void SendScannerCmd(string cmd)
        {
            try
            {
                if (!_serialPort.IsOpen) return;
                lock (this)
                {
                    Thread.Sleep(150);
                    _serialPort.Write(cmd);
                }
            }
            catch (Exception)
            {
                
            }
           
        }
        #endregion
        #endregion

        #region 触发、处理温度异常

        public override void TemperatureAbnormal()
        {
            _warningDicionary.Add(WarningType.温度异常, false);
            Task.Run(() =>
            {
                while (_temperatureValue  < 100)
                {
                    _temperatureValue += 3;
                    _labelTemperatureItem.Write(_temperatureValue);
                    SpTemperatureValue(_temperatureValue);
                    Thread.Sleep(_sleepfast);
                }
                BeginWarning(WarningType.温度异常);
                _flashWarningItem.StartFlow();
                HandleTempretureAbnormal();
            });
        }
        private void HandleTempretureAbnormal()
        {
            Task.Run(
                () =>
                {
                    OpenColdValve();
                    StopWarning(WarningType.温度异常);
                    _warningDicionary[WarningType.温度异常] = true;
                });
        }

        private void OpenColdValve()
        {
            while (!_listenCts.IsCancellationRequested)
            {
                if (_temperatureValue <= 50)
                {
                    AddCompose("处理温度异常：打开冷水阀");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
        }
        #endregion

        #region 泄漏

        public override void LeakageAbnormal()
        {
            _isleakAbnormal = false;
            BeginWarning(WarningType.泄漏);
            BeginLeak();
            _warningDicionary.Add(WarningType.泄漏, false);
            HandleLeakAbnormal();
        }

        private void HandleLeakAbnormal()
        {
            //打开急停按钮
            while (!_listenCts.IsCancellationRequested)
            {
                if (_valveStopState)
                {
                    AddCompose("处理泄漏异常：按下急停按钮");
                    break;
                }
                Thread.Sleep(_sleepfast);
            }
            //关闭电机
            Parallel.Invoke(
             () =>
            {
                while (!_listenCts.IsCancellationRequested)
                {
                    if (!_valveStirState)
                    {
                        AddCompose("处理泄漏异常：关闭搅拌电机");
                        break;
                    }
                    Thread.Sleep(_sleepfast);
                }
            });

            StopWarning(WarningType.泄漏);
            _warningDicionary[WarningType.泄漏] = true;
        }

        #endregion

        #region 重写公共方法
        public override void Begin()
        {
            ListenOPCRelation();//联动
        }

        private void ListenOPCRelation()
        {
            ThreadPool.QueueUserWorkItem((o) =>
            {
                #region 空气鼓风机
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputO2State > 0)
                        {
                            _flowOxygenItem.StartFlow();
                            //if (!Isinner) 
                                _valveOxygenItem.Open();
                            var tempflow = _inputO2State*10;
                            if (tempflow > _flowOxygenValue)
                            {
                                _flowOxygenValue += 1;
                            }
                            else if(tempflow<_flowOxygenValue)
                            {
                                _flowOxygenValue -= 1;
                            }
                            _labelFlowOxygenItem.Write(_flowOxygenValue);
                        }
                        else
                        {
                            _flowOxygenItem.StopFlow();
                            //if (!Isinner) 
                                _valveOxygenItem.Close();
                            _flowOxygenValue = 0;
                            _labelFlowOxygenItem.Write(_flowOxygenValue);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 通入SO3
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputSo3State > 0)
                        {
                            _flowSo3Item.StartFlow();
                            //if (!Isinner)
                                _valveSo3Item.Open();
                            var tempflow = _inputSo3State * 10;
                            if (tempflow > _flowSo3Value)
                            {
                                _flowSo3Value += 1;
                            }
                            else if (tempflow < _flowSo3Value)
                            {
                                _flowSo3Value -= 1;
                            }
                            _labelFlowSo3Item.Write(_flowSo3Value);
                        }
                        else
                        {
                            _flowSo3Item.StopFlow();
                            //if (!Isinner)
                                _valveSo3Item.Close();
                            _flowSo3Value = 0;
                            _labelFlowSo3Item.Write(_flowSo3Value);
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 烷基苯
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_inputbenState > 0)
                        {
                            _flowAlkylbenzeneItem.StartFlow();
                            //if (!Isinner)
                                _valveAlkylbenzeneItem.Open();
                            var tempflow = _inputbenState*10;
                            if (tempflow > _flowAlkylbenzeneValue)
                            {
                                _flowAlkylbenzeneValue += 1;
                            }
                            else if (tempflow < _flowAlkylbenzeneValue)
                            {
                                _flowAlkylbenzeneValue -= 1;
                            }
                            _labelFlowAlkylbenzeneItem.Write(_flowAlkylbenzeneValue);
                        }
                        else
                        {
                            _flowAlkylbenzeneItem.StopFlow();
                            //if (!Isinner) 
                                _valveAlkylbenzeneItem.Close();

                            _flowAlkylbenzeneValue = 0;
                            _labelFlowAlkylbenzeneItem.Write(_flowAlkylbenzeneValue);
                        }

                        SpFlowValue(2, _flowAlkylbenzeneValue);
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 计算比例
                Task.Run(() =>
                {
                    bool isopened=false;
                    while (!_listenCts.IsCancellationRequested)
                    {
                        //So3:O2比例  规定：[2,7]
                        if (_inputO2State > 0 && _inputSo3State > 0)
                        {
                            _flowInreactorItem.StartFlow();
                            var r1 = _inputSo3State/_inputO2State;
                            _so3O2Rate = Math.Round(r1, 2);
                            //if (r1 > _so3O2Rate)
                            //{
                            //    _so3O2Rate += 0.02;
                            //}
                            //else if (r1 < _so3O2Rate)
                            //{
                            //    _so3O2Rate -= 0.02;
                            //}

                            _labelRateSo3O2Item.Write(_so3O2Rate);
                            SpAIvalue(3, _so3O2Rate);
                        }
                        else
                        {
                            _flowInreactorItem.StopFlow();
                        }

                        //苯:So3      规定[0.8-1.2] 
                        if (_inputSo3State > 0 && _inputbenState > 0)
                        {
                            isopened = true;
                            var r2 = _inputbenState/_inputSo3State;
                            _alkylbenzeneSo3Rate = Math.Round(r2, 2);
                            //if (r2 > _alkylbenzeneSo3Rate)
                            //{
                            //    _alkylbenzeneSo3Rate += 0.02;
                            //}
                            //else if (r2 < _alkylbenzeneSo3Rate)
                            //{
                            //    _alkylbenzeneSo3Rate -= 0.02;
                            //}
                            _labelRateBenSo3Item.Write(_alkylbenzeneSo3Rate);
                            
                        }
                       
                        //_benSo3Rate_creament = _alkylbenzeneSo3Rate < 0.8 ? 0.1 : 0.01;

                        ////苯:So3      规定[0.8-1.2] 实际[0.6,1.2]
                        //if (_valveSo3State && _valveAlkylbenzeneState)
                        //{
                        //    isopened = true;
                        //    _alkylbenzeneSo3Rate += _benSo3Rate_creament;
                        //    if (_alkylbenzeneSo3Rate > 1.2)
                        //        _alkylbenzeneSo3Rate = 1.2;

                        //    _labelRateBenSo3Item.Write(_alkylbenzeneSo3Rate);
                        //    SpAIvalue(2, _alkylbenzeneSo3Rate);
                           
                        //}
                        //else
                        //{
                        //    if (isopened)
                        //    {
                        //        _alkylbenzeneSo3Rate -= _benSo3Rate_creament;
                        //        if (_alkylbenzeneSo3Rate <= 0.6)
                        //            _alkylbenzeneSo3Rate = 0.6;
                        //        _labelRateBenSo3Item.Write(_alkylbenzeneSo3Rate);
                        //        SpAIvalue(2, _alkylbenzeneSo3Rate);
                        //    }
                        //}
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 冷水阀
                Task.Run(() =>
                {
                    //温度 规定[40,50]   实际[25,60]
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveColdState)
                        {
                            if (!Isinner) _valveColdItem.Open();
                            _flowInColdItem.StartFlow();
                            
                            //反应完成，有液位产生
                            if (_temperatureValue > 45)
                            {
                                _kettleLevel = 1;
                                _labelColorItem.Write(_kettleLevel);
                            }


                            if (_temperatureValue < 51)//51
                            {
                                StopWarning (WarningType.温度过高);
                                _flashTemperatureItem.StopFlow();
                            }

                            _temperatureValue -= _temperature_decrement;
                            _temperature_decrement = _temperatureValue < 25 ? 0 : 0.3;

                            _labelTemperatureItem.Write(_temperatureValue);
                            SpTemperatureValue(_temperatureValue);
                        }
                        else
                        {
                            if (!Isinner) _valveColdItem.Close();
                            _flowInColdItem.StopFlow();

                            //if (_valveOxygenState && _valveSo3State && _valveAlkylbenzeneState)
                            if (_inputO2State>0 && _inputSo3State>0 && _inputbenState>0)
                            {
                                _temperatureValue += _temperature_increment;
                                _temperature_increment = _temperatureValue < 40 ? 0.8 : 0.1;

                                _labelTemperatureItem.Write(_temperatureValue);
                                SpTemperatureValue(_temperatureValue);

                                if (_temperatureValue>51)//51
                                {
                                    BeginWarning(WarningType.温度过高);
                                    _flashTemperatureItem.StartFlow();
                                }

                            }                           
                        }

                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 循环泵 左侧
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveLeftCycleState && _valveStirState)
                        {
                            _flowLeftCycleItem.StartFlow();
                            if (!Isinner) _valveLeftCycleItem.Open();
                        }
                        else
                        {
                            _flowLeftCycleItem.StopFlow();
                            if (!Isinner)
                            {
                                _valveLeftCycleItem.Close();
                            }
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 循环泵 右侧
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveRightCycleState && _valveStirState)
                        {
                            _flowRightCycleItem.StartFlow();
                            if (!Isinner)
                            {
                                _valveRightCycleItem.Open();
                            }
                        }
                        else
                        {
                            _flowRightCycleItem.StopFlow();
                            if (!Isinner)
                            {
                                _valveRightCycleItem.Close();
                            }
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

                #region 老化器
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveInAgerState && _valveStirState)
                        {
                            _flowInAgerItem.StartFlow();
                            if (!Isinner)
                            {
                                _valveAgerItem.Open();
                            }
                        }
                        else
                        {
                            _flowInAgerItem.StopFlow();
                            if (!Isinner)
                            {
                                _valveAgerItem.Close();
                            }
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion


                #region 电机搅拌
                Task.Run(() =>
                {
                    while (!_listenCts.IsCancellationRequested)
                    {
                        if (_valveStirState)
                        {
                           if(!Isinner) _valveStirItem.Open();
                            BeginStir();
                        }
                        else
                        {
                            if (!Isinner) _valveStirItem.Close();
                            StopStir();
                        }
                        Thread.Sleep(_sleepfast);
                    }
                });
                #endregion

               

            });
        }

        public override async Task<string> CheckDefault()
        {
            StringBuilder builder = new StringBuilder();
            await Task.Run(() =>
            {
                if (!Isinner)
                {
                    while (!_isgetoverstate1 || !_isgetoverstate2)
                    {
                        Thread.Sleep(_sleepfast);
                    }
                }
                else
                {
                    // Thread.Sleep(4000);
                    while (!_isListenSingnalover)
                    {
                        Thread.Sleep(_sleepfast);
                    }
                }
                
                if (_valveOxygenState)
                    builder.AppendLine("空气鼓风机未关闭");
                if (_valveSo3State)
                    builder.AppendLine("SO3进料阀未关闭");
                if (_valveAlkylbenzeneState)
                    builder.AppendLine("十二烷基苯进料调节阀阀未关闭");
                if (_valveColdState)
                    builder.AppendLine("冷水调节阀未关闭");
                if (_valveLeftCycleState)
                    builder.AppendLine("下行循环泵未关闭");
                if (_valveRightCycleState)
                    builder.AppendLine("上行循环泵未关闭");
                if (_valveInAgerState)
                    builder.AppendLine("老化器阀门未关闭");
                if (_valveStirState)
                    builder.AppendLine("循环泵按钮未关闭");
                if (_valveStopState)
                     builder.AppendLine("急停按钮未复位");                   
                
            });

            await InitServerData();
            if (_details == null || _abnormals == null)
                builder.AppendLine("可能由于网络原因，导致获取数据失败，请点击\"确定\"按钮 尝试重新获取");

            return builder.ToString();
        }

        
        public override void Over()
        {
            Close();
            CalcFlowAndStep();
            _listenCts.Cancel();
            Score = CalcScore();
            CloseAllRelay();
            Finish();
        }

        public override void Close()
        {
            this._listenCts.Cancel();
            base.Close();
            if (_serialPort != null)
            {
                _serialPort.DataReceived -= _serialPort_DataReceived;
                _serialPort.Close();
            }
        }
        private void CalcFlowAndStep()
        {
            #region 解析步骤

            //1. 计算比例
            var avg_So3o2_count = _steps.Count(i => i.Status[StatusName.空气阀门]>0 && i.Status[StatusName.So3阀门]>0);
            var avg_So3o2 = avg_So3o2_count > 0
                ? _steps.Where(i => i.Status[StatusName.空气阀门] > 0 && i.Status[StatusName.So3阀门] > 0)
                    .Average(i => i.Status[StatusName.So3O2比例])
                : -1;

            var avg_benSo3_count =
                _steps.Count(i => i.Status[StatusName.十二烷基苯阀门] > 0 && i.Status[StatusName.So3阀门] > 0);
            var avg_benSo3 = avg_benSo3_count > 0
                ? _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] > 0 && i.Status[StatusName.So3阀门] > 0)
                    .Average(i => i.Status[StatusName.苯So3比例])
                : -1;

            //2.计算温度
            var avg_temp_count =
                _steps.Count(
                    i =>
                        i.Status[StatusName.十二烷基苯阀门] > 0 && i.Status[StatusName.So3阀门] > 0 &&
                        i.Status[StatusName.空气阀门] > 0);
            var avg_temperature = avg_temp_count > 0
                ? _steps.Where(
                    i =>
                        i.Status[StatusName.十二烷基苯阀门] > 0 && i.Status[StatusName.So3阀门] > 0 &&
                        i.Status[StatusName.空气阀门] > 0)
                    .Average(i => i.Status[StatusName.温度])
                : -1;

            //2. 反应温度
            var avg_reactiontemperature_items = _steps.Where(i => i.Status[StatusName.温度] >40);


            //3.反应完 液位标识
            var levelItem =
                _steps.Where(i => i.Status[StatusName.反应器底部液位] == 1).OrderBy(i => i.Date).FirstOrDefault();

            //4.启动循环泵
            var stir_first_open_item = _steps.Where(i => i.Status[StatusName.循环泵阀门] == _open).OrderBy(i => i.Date).FirstOrDefault();

            var stir_left_firstopen_item = _steps.Where(i => i.Status[StatusName.左循环阀门] == _open).OrderBy(i => i.Date).FirstOrDefault();

            var stir_right_firstopen_item = _steps.Where(i => i.Status[StatusName.右循环阀门] == _open).OrderBy(i => i.Date).FirstOrDefault();

            var stir_old_firstopen_item = _steps.Where(i => i.Status[StatusName.老化器阀门] == _open).OrderBy(i => i.Date).FirstOrDefault();

            //5. 停车 ,关闭阀门 ：最后一次打开的下一个step
            var oxygen_lastopen_item = _steps.Where(i => i.Status[StatusName.空气阀门] > 0).OrderByDescending(i => i.Date).FirstOrDefault();
            var oxygen_close_item =oxygen_lastopen_item!=null? _steps.Where(i => i.Status[StatusName.空气阀门]==0
                && i.Date>oxygen_lastopen_item.Date).OrderBy(i => i.Date).FirstOrDefault():null;

            var so3_lastopen_item = _steps.Where(i => i.Status[StatusName.So3阀门] > 0).OrderByDescending(i => i.Date).FirstOrDefault();
            var so3_close_item = so3_lastopen_item != null ? _steps.Where(i => i.Status[StatusName.So3阀门] == 0
                && i.Date > so3_lastopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;

            var ben_lastopen_item = _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] > 0).OrderByDescending(i => i.Date).FirstOrDefault();
            var ben_close_item = ben_lastopen_item != null ? _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] == 0
                && i.Date > ben_lastopen_item.Date).OrderBy(i => i.Date).FirstOrDefault() : null;

            // 降温到室温 [25] 
            //var low_temperature_item =levelItem!=null? _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] == _close 
            //    && i.Status[StatusName.So3阀门] == _close && i.Status[StatusName.空气阀门] == _close
            //    && i.Date>levelItem.Date)
            //    .OrderByDescending(i => i.Date).FirstOrDefault() : null ;

            var last_low_temperature_item = levelItem != null ? _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] == 0
                && i.Status[StatusName.So3阀门] == 0 && i.Status[StatusName.空气阀门] == 0
                && i.Date > levelItem.Date)
                .OrderByDescending(i => i.Date).FirstOrDefault() : null;




            var low_temperature_item = levelItem != null ? _steps.Where(i => i.Status[StatusName.十二烷基苯阀门] == 0
                && i.Status[StatusName.So3阀门] ==0 && i.Status[StatusName.空气阀门] ==0
                && i.Date > levelItem.Date
                && i.Status[StatusName.温度] == last_low_temperature_item.Status[StatusName.温度]
                ).OrderBy(i => i.Date).FirstOrDefault() : null;
             


            //之后关闭循环泵和循环水
            //var stir_close_item = _steps.Where(i => i.Status[StatusName.循环泵阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var stir_lastopen_item = _steps.Where(i => i.Status[StatusName.循环泵阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var stir_close_item = stir_lastopen_item != null
                ? _steps.Where(i => i.Status[StatusName.循环泵阀门] == _close)
                    .OrderByDescending(i => i.Date)
                    .FirstOrDefault()
                : null;

            //var cold_close_item = _steps.Where(i => i.Status[StatusName.冷却水阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var cold_lastopen_item = _steps.Where(i => i.Status[StatusName.冷却水阀门] == _open).OrderByDescending(i => i.Date).FirstOrDefault();
            var cold_close_item = cold_lastopen_item != null
                ? _steps.Where(i => i.Status[StatusName.冷却水阀门] == _close).OrderByDescending(i => i.Date).FirstOrDefault()
                : null;

            #endregion

            #region 添加步骤
            //1. 比例 So3:O2 = [2-7]
            if (avg_So3o2 != -1)
            {
                if (avg_So3o2 >= 2 && avg_So3o2 <= 7)
                {
                    AddCompose("So3:O2比例2-7vol%");
                }
                else
                {
                    AddCompose("So3:O2比例不在2-7vol%");
                }
            }

            //苯：So3 = [0.8,1.2]
            if (avg_benSo3 != -1)
            {
                if (avg_benSo3 >= 0.8 && avg_benSo3 < 1.2)
                {
                    AddCompose("十二烷基苯:So3比例正确");
                }
                else
                {
                    AddCompose("十二烷基苯:So3比例不正确");
                }
            }

            bool isreactionover = false;
            //2.反应温度 和 反应时间
            if (avg_temperature != -1)
            {
                if (avg_temperature >= 36 && avg_temperature <= 50)
                {
                    AddCompose("反应温度40～50℃");
                }
                else
                {
                    AddCompose("反应温度不在40～50℃之间");
                }
            }

            //2.1反应时间
            if (avg_reactiontemperature_items.Any())
            {
                var avg_count = avg_reactiontemperature_items.Count();
                var reaction_sencond = avg_count/2;
                if (reaction_sencond > _reactionSecond)
                {
                    AddCompose("反应时间正常");
                    isreactionover = true;
                }
                else
                {
                    AddCompose("反应时间不足");
                }
            }

            //3.反应完 打开循环泵 ，下料上料老化器阀门
            if (stir_first_open_item != null &&levelItem!=null)
            {
                AddCompose(stir_first_open_item.Date > levelItem.Date && isreactionover ? "反应完成：反应器底部有液位，启动循环泵" : "反应器底部无液位或反应未完成，启动循环泵");
            }
            if (stir_left_firstopen_item != null &&levelItem!=null)
            {
                AddCompose(stir_left_firstopen_item.Date > levelItem.Date ? "反应完成：反应器底部有液位，启动循环泵下料阀" : "反应器底部无液位或反应未完成，启动循环泵下料阀");
            }
            if (stir_right_firstopen_item != null &&levelItem!=null)
            {
                AddCompose(stir_right_firstopen_item.Date > levelItem.Date ? "反应完成：反应器底部有液位，启动循环泵上料阀" : "反应器底部无液位或反应未完成，启动循环泵上料阀");
            }
            if (stir_old_firstopen_item != null &&levelItem!=null)
            {
                AddCompose(stir_old_firstopen_item.Date > levelItem.Date ? "反应完成：反应器底部有液位，启动循环泵老化器阀门" : "反应器底部无液位或反应未完成，启动循环泵老化器阀门");
            }

            //4.停车  按程序关闭三氧化硫、十二烷基苯磺酸和干空气进料调节阀门
            if (so3_close_item != null  && ben_close_item!=null)
            {
                if (so3_close_item.Date < ben_close_item.Date)
                    AddCompose("停车，关闭So3进料调节阀门");
                else
                    AddCompose("停车，关闭So3进料调节阀门，关闭顺序错误");
            }

            if (oxygen_close_item != null && ben_close_item != null)
            {
                if (ben_close_item.Date < oxygen_close_item.Date)
                {
                    AddCompose("停车，关闭十二烷基苯进料调节阀门");
                    AddCompose("停车，关闭干空气进料调节阀门");
                }
                else
                    AddCompose("停车，关闭十二烷基苯进料调节阀门，关闭顺序错误");
            }
            
            if (low_temperature_item != null)
            {
                Console.WriteLine("温度"+low_temperature_item.Status[StatusName.温度]);
                AddCompose(low_temperature_item.Status[StatusName.温度] < 30 ? "反应器温度降到室温" : "反应器温度未降到室温");

                if (stir_close_item != null)
                {
                    if (stir_close_item.Date > low_temperature_item.Date)
                    {
                        AddCompose("降温后关闭循环泵");
                    }
                }

                if (cold_close_item != null)
                {
                    if(cold_close_item.Date>low_temperature_item.Date)
                        AddCompose("降温后关闭循环水阀");
                }
            }

            
            #endregion
        }

        

        #endregion


        #region 串口数据

        void SpFlowValue(int index,double value)
        {
            WriteFlowValue(_llcmd, index, value);
        }

        void SpPressureValue(double value)
        {
            WritePressureValue(_ylcmd, value);
        }

        void SpTemperatureValue(double value)
        {            
            WriteAIvalue(_aicmd, 1, value);
        }

        void SpAIvalue(int index,double value)
        {
            WriteAIvalue(_aicmd, index, value);
        }
        #endregion

        #region 操作继电器
        /// <summary>
        /// 写继电器
        /// </summary>
        /// <param name="number">0-128， </param>
        void SPWriteTool(int number)
        {
            if (Isinner) return;
            WriteTool(_relaycmd, number);
        }

        void CloseAllRelay()
        {
            SPWriteTool(0);
        }

        /// <summary>
        /// 开始预警
        /// </summary>
        /// <param name="type">预警类型</param>
        void BeginWarning(WarningType type)
        {
            if (!_warningtypes.Contains(type))
            {
                _flashWarningItem.Open();
                _warningtypes.Add(type);
                _relayCommand = _relayCommand | _warning1number;
                _relayCommand = _relayCommand | _warning2number;
                SPWriteTool(_relayCommand);
            }
        }

        void StopWarning(WarningType type)
        {
            if (_warningtypes.Contains(type))
            {
                _flashWarningItem.Close();
                _relayCommand = (~_warning1number) & _relayCommand;
                _relayCommand = (~_warning2number) & _relayCommand;
                SPWriteTool(_relayCommand);
                _warningtypes.Remove(type);
            }
        }

        /// <summary>
        /// 开始泄漏
        /// </summary>
        void BeginLeak()
        {
            _flashWarningItem.Open();
            _relayCommand = _relayCommand | _fognumber;
            SPWriteTool(_relayCommand);
            Thread.Sleep(500);
            StopLeak();
        }
        /// <summary>
        /// 停止泄漏
        /// </summary>
        void StopLeak()
        {
            _flashWarningItem.Close();
            _relayCommand = _relayCommand & (~_fognumber);
            SPWriteTool(_relayCommand);
        }

        void BeginStir()
        {
            _relayCommand = _relayCommand | _stirnumber;
            SPWriteTool(_relayCommand);
        }

        void StopStir()
        {
            _relayCommand = _relayCommand & (~_stirnumber);
            SPWriteTool(_relayCommand);
        }
        #endregion

        #region 枚举定义

        enum StatusName
        {
            温度,  反应器底部液位,So3O2比例,苯So3比例,
            空气阀门,
            So3阀门, 十二烷基苯阀门, 冷却水阀门, 左循环阀门, 右循环阀门, 老化器阀门,循环泵阀门,
           急停按钮,
        }

        enum FiledName
        {
            //阀门
            ValveO2, ValveSO3, ValveBenzene, ValveCold, ValveLeftCycle, ValveRightCycle, ValveAger,
            //管道
            FlowO2, FlowSO3, FlowBenzene, FlowSO3_O2, FlowCold, FlowLeftCycle, FlowRightCycle, FlowAger, FlowIndemist,
            //标签
            LabelO2, LabelSO3, LabelBenzene, LabelSO3_O2, LabelSO3_Benzene, LabelTemperature,
            //闪烁
            FlashTemperature, FlashWarning,
            ValveStir,
            ValveStop,
            LabelColor,
            InputO2,
            InputSo3,
            InputBen
        }

        enum WarningType
        {
            温度过高, 压力异常,

            泄漏,
            温度异常
        }
        class Step
        {
            public Dictionary<StatusName, double> Status = new Dictionary<StatusName, double>();

            public DateTime Date
            {
                get;
                set;
            }
        } 
        #endregion



    }

   
}
